package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.*;
import com.zhentao.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品管理控制器
 * @date: 2025/8/13 9:21
 * @author: ftt
 */
@RestController
@RequestMapping("/product")
@CrossOrigin
public class ProductController {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Autowired
    private ProductAttributeMapper productAttributeMapper;

    // ==================== 商品类别管理 ====================

    /**
     * 分页查询商品类别列表
     */
    @GetMapping("/category/list")
    public Page<ProductCategory> getCategoryList(@RequestParam(defaultValue = "1") Integer current,
                                                @RequestParam(defaultValue = "10") Integer size,
                                                @RequestParam(required = false) String name,
                                                @RequestParam(required = false) Integer status) {
        Page<ProductCategory> page = new Page<>(current, size);
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
        
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByAsc("sort", "id");
        return productCategoryMapper.selectPage(page, queryWrapper);
    }

    /**
     * 获取所有商品类别（用于下拉选择）
     */
    @GetMapping("/category/all")
    public List<ProductCategory> getAllCategories() {
        QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("sort", "id");
        return productCategoryMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID查询商品类别详情
     */
    @GetMapping("/category/{id}")
    public Map<String, Object> getCategoryById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        ProductCategory category = productCategoryMapper.selectById(id);
        
        if (category != null) {
            result.put("success", true);
            result.put("data", category);
        } else {
            result.put("success", false);
            result.put("message", "商品类别不存在");
        }
        return result;
    }

    /**
     * 新增商品类别
     */
    @PostMapping("/category/add")
    public Map<String, Object> addCategory(@RequestBody ProductCategory category) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            category.setTenantId(1L);
            category.setCreateTime(new Date());
            category.setUpdateTime(new Date());
            
            productCategoryMapper.insert(category);
            
            result.put("success", true);
            result.put("message", "商品类别创建成功");
            result.put("id", category.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品类别创建失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新商品类别
     */
    @PutMapping("/category/update")
    public Map<String, Object> updateCategory(@RequestBody ProductCategory category) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            category.setUpdateTime(new Date());
            productCategoryMapper.updateById(category);
            
            result.put("success", true);
            result.put("message", "商品类别更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品类别更新失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除商品类别
     */
    @DeleteMapping("/category/{id}")
    public Map<String, Object> deleteCategory(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查是否有子类别
            QueryWrapper<ProductCategory> childWrapper = new QueryWrapper<>();
            childWrapper.eq("parent_id", id);
            long childCount = productCategoryMapper.selectCount(childWrapper);
            
            if (childCount > 0) {
                result.put("success", false);
                result.put("message", "该类别下有子类别，无法删除");
                return result;
            }
            
            // 检查是否有关联的商品
            QueryWrapper<Product> productWrapper = new QueryWrapper<>();
            productWrapper.eq("category_id", id);
            long productCount = productMapper.selectCount(productWrapper);
            
            if (productCount > 0) {
                result.put("success", false);
                result.put("message", "该类别下有商品，无法删除");
                return result;
            }
            
            productCategoryMapper.deleteById(id);
            result.put("success", true);
            result.put("message", "商品类别删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品类别删除失败: " + e.getMessage());
        }
        
        return result;
    }

    // ==================== 商品信息管理 ====================

    /**
     * 分页查询商品列表
     */
    @GetMapping("/list")
    public Page<Product> getProductList(@RequestParam(defaultValue = "1") Integer current,
                                       @RequestParam(defaultValue = "10") Integer size,
                                       @RequestParam(required = false) String name,
                                       @RequestParam(required = false) String barcode,
                                       @RequestParam(required = false) Long categoryId,
                                       @RequestParam(required = false) Integer status) {
        Page<Product> page = new Page<>(current, size);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (barcode != null && !barcode.trim().isEmpty()) {
            queryWrapper.like("barcode", barcode);
        }
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByDesc("id");
        return productMapper.selectPage(page, queryWrapper);
    }

    /**
     * 根据ID查询商品详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getProductById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        Product product = productMapper.selectById(id);
        if (product == null) {
            result.put("success", false);
            result.put("message", "商品不存在");
            return result;
        }
        
        // 查询商品属性
        QueryWrapper<ProductAttribute> attrWrapper = new QueryWrapper<>();
        attrWrapper.eq("product_id", id);
        List<ProductAttribute> attributes = productAttributeMapper.selectList(attrWrapper);
        
        result.put("success", true);
        result.put("product", product);
        result.put("attributes", attributes);
        
        return result;
    }

    /**
     * 新增商品
     */
    @PostMapping("/add")
    public Map<String, Object> addProduct(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 解析商品信息
            Product product = new Product();
            product.setName(request.get("name").toString());
            product.setBarcode(request.get("barcode") != null ? request.get("barcode").toString() : "");
            product.setCategoryId(Long.valueOf(request.get("categoryId").toString()));
            product.setSpec(request.get("spec") != null ? request.get("spec").toString() : "");
            product.setModel(request.get("model") != null ? request.get("model").toString() : "");
            product.setUnitId(Long.valueOf(request.get("unitId").toString()));
            product.setAttributes(request.get("attributes") != null ? request.get("attributes").toString() : "");
            product.setStatus(Integer.valueOf(request.get("status").toString()));
            product.setRemark(request.get("remark") != null ? request.get("remark").toString() : "");
            product.setTenantId(1L);
            product.setCreateTime(new Date());
            product.setUpdateTime(new Date());
            
            productMapper.insert(product);
            
            // 处理商品属性
            List<Map<String, Object>> attributes = (List<Map<String, Object>>) request.get("attributeList");
            if (attributes != null && !attributes.isEmpty()) {
                for (Map<String, Object> attr : attributes) {
                    ProductAttribute productAttribute = new ProductAttribute();
                    productAttribute.setProductId(product.getId());
                    productAttribute.setAttrName(attr.get("attrName").toString());
                    productAttribute.setAttrValue(attr.get("attrValue").toString());
                    productAttribute.setTenantId(1L);
                    productAttribute.setCreateTime(new Date());
                    productAttribute.setUpdateTime(new Date());
                    
                    productAttributeMapper.insert(productAttribute);
                }
            }
            
            result.put("success", true);
            result.put("message", "商品创建成功");
            result.put("id", product.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品创建失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新商品
     */
    @PutMapping("/update")
    public Map<String, Object> updateProduct(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Long productId = Long.valueOf(request.get("id").toString());
            
            // 更新商品信息
            Product product = new Product();
            product.setId(productId);
            product.setName(request.get("name").toString());
            product.setBarcode(request.get("barcode") != null ? request.get("barcode").toString() : "");
            product.setCategoryId(Long.valueOf(request.get("categoryId").toString()));
            product.setSpec(request.get("spec") != null ? request.get("spec").toString() : "");
            product.setModel(request.get("model") != null ? request.get("model").toString() : "");
            product.setUnitId(Long.valueOf(request.get("unitId").toString()));
            product.setAttributes(request.get("attributes") != null ? request.get("attributes").toString() : "");
            product.setStatus(Integer.valueOf(request.get("status").toString()));
            product.setRemark(request.get("remark") != null ? request.get("remark").toString() : "");
            product.setUpdateTime(new Date());
            
            productMapper.updateById(product);
            
            // 删除原有属性
            QueryWrapper<ProductAttribute> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("product_id", productId);
            productAttributeMapper.delete(deleteWrapper);
            
            // 插入新属性
            List<Map<String, Object>> attributes = (List<Map<String, Object>>) request.get("attributeList");
            if (attributes != null && !attributes.isEmpty()) {
                for (Map<String, Object> attr : attributes) {
                    ProductAttribute productAttribute = new ProductAttribute();
                    productAttribute.setProductId(productId);
                    productAttribute.setAttrName(attr.get("attrName").toString());
                    productAttribute.setAttrValue(attr.get("attrValue").toString());
                    productAttribute.setTenantId(1L);
                    productAttribute.setCreateTime(new Date());
                    productAttribute.setUpdateTime(new Date());
                    
                    productAttributeMapper.insert(productAttribute);
                }
            }
            
            result.put("success", true);
            result.put("message", "商品更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品更新失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteProduct(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 删除商品属性
            QueryWrapper<ProductAttribute> attrWrapper = new QueryWrapper<>();
            attrWrapper.eq("product_id", id);
            productAttributeMapper.delete(attrWrapper);
            
            // 删除商品
            productMapper.deleteById(id);
            
            result.put("success", true);
            result.put("message", "商品删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品删除失败: " + e.getMessage());
        }
        
        return result;
    }

    // ==================== 计量单位管理 ====================

    /**
     * 分页查询计量单位列表
     */
    @GetMapping("/unit/list")
    public Page<Unit> getUnitList(@RequestParam(defaultValue = "1") Integer current,
                                  @RequestParam(defaultValue = "10") Integer size,
                                  @RequestParam(required = false) String name,
                                  @RequestParam(required = false) String type,
                                  @RequestParam(required = false) Integer status) {
        Page<Unit> page = new Page<>(current, size);
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (type != null && !type.trim().isEmpty()) {
            queryWrapper.eq("type", type);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByAsc("sort", "id");
        return unitMapper.selectPage(page, queryWrapper);
    }

    /**
     * 获取所有计量单位（用于下拉选择）
     */
    @GetMapping("/unit/all")
    public List<Unit> getAllUnits() {
        QueryWrapper<Unit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("sort", "id");
        return unitMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID查询计量单位详情
     */
    @GetMapping("/unit/{id}")
    public Map<String, Object> getUnitById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        Unit unit = unitMapper.selectById(id);
        
        if (unit != null) {
            result.put("success", true);
            result.put("data", unit);
        } else {
            result.put("success", false);
            result.put("message", "计量单位不存在");
        }
        return result;
    }

    /**
     * 新增计量单位
     */
    @PostMapping("/unit/add")
    public Map<String, Object> addUnit(@RequestBody Unit unit) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            unit.setTenantId(1L);
            unit.setCreateTime(new Date());
            unit.setUpdateTime(new Date());
            
            unitMapper.insert(unit);
            
            result.put("success", true);
            result.put("message", "计量单位创建成功");
            result.put("id", unit.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "计量单位创建失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新计量单位
     */
    @PutMapping("/unit/update")
    public Map<String, Object> updateUnit(@RequestBody Unit unit) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            unit.setUpdateTime(new Date());
            unitMapper.updateById(unit);
            
            result.put("success", true);
            result.put("message", "计量单位更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "计量单位更新失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除计量单位
     */
    @DeleteMapping("/unit/{id}")
    public Map<String, Object> deleteUnit(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查是否有关联的商品
            QueryWrapper<Product> productWrapper = new QueryWrapper<>();
            productWrapper.eq("unit_id", id);
            long productCount = productMapper.selectCount(productWrapper);
            
            if (productCount > 0) {
                result.put("success", false);
                result.put("message", "该计量单位下有商品，无法删除");
                return result;
            }
            
            unitMapper.deleteById(id);
            result.put("success", true);
            result.put("message", "计量单位删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "计量单位删除失败: " + e.getMessage());
        }
        
        return result;
    }

    // ==================== 商品属性管理 ====================

    /**
     * 分页查询商品属性列表
     */
    @GetMapping("/attribute/list")
    public Page<ProductAttribute> getAttributeList(@RequestParam(defaultValue = "1") Integer current,
                                                  @RequestParam(defaultValue = "10") Integer size,
                                                  @RequestParam(required = false) Long productId,
                                                  @RequestParam(required = false) String attrName,
                                                  @RequestParam(required = false) String attrValue) {
        Page<ProductAttribute> page = new Page<>(current, size);
        QueryWrapper<ProductAttribute> queryWrapper = new QueryWrapper<>();
        
        if (productId != null && productId > 0) {
            queryWrapper.eq("product_id", productId);
        }
        if (attrName != null && !attrName.trim().isEmpty()) {
            queryWrapper.like("attr_name", attrName);
        }
        if (attrValue != null && !attrValue.trim().isEmpty()) {
            queryWrapper.like("attr_value", attrValue);
        }
        
        queryWrapper.orderByDesc("id");
        return productAttributeMapper.selectPage(page, queryWrapper);
    }

    /**
     * 根据商品ID查询属性列表
     */
    @GetMapping("/attribute/{productId}")
    public List<ProductAttribute> getAttributesByProductId(@PathVariable Long productId) {
        QueryWrapper<ProductAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.orderByAsc("id");
        return productAttributeMapper.selectList(queryWrapper);
    }

    /**
     * 新增商品属性
     */
    @PostMapping("/attribute/add")
    public Map<String, Object> addAttribute(@RequestBody ProductAttribute attribute) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            attribute.setTenantId(1L);
            attribute.setCreateTime(new Date());
            attribute.setUpdateTime(new Date());
            
            productAttributeMapper.insert(attribute);
            
            result.put("success", true);
            result.put("message", "商品属性创建成功");
            result.put("id", attribute.getId());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品属性创建失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新商品属性
     */
    @PutMapping("/attribute/update")
    public Map<String, Object> updateAttribute(@RequestBody ProductAttribute attribute) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            attribute.setUpdateTime(new Date());
            productAttributeMapper.updateById(attribute);
            
            result.put("success", true);
            result.put("message", "商品属性更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品属性更新失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除商品属性
     */
    @DeleteMapping("/attribute/{id}")
    public Map<String, Object> deleteAttribute(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();

        try {
            productAttributeMapper.deleteById(id);
            result.put("success", true);
            result.put("message", "商品属性删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "商品属性删除失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 获取所有可用的属性名（用于下拉选择）
     */
    @GetMapping("/attribute/names")
    public List<String> getAllAttributeNames() {
        QueryWrapper<ProductAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT attr_name");
        queryWrapper.orderByAsc("attr_name");
        List<ProductAttribute> attributes = productAttributeMapper.selectList(queryWrapper);
        
        return attributes.stream()
                .map(ProductAttribute::getAttrName)
                .filter(name -> name != null && !name.trim().isEmpty())
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 根据属性名获取所有可用的属性值（用于下拉选择）
     */
    @GetMapping("/attribute/values/{attrName}")
    public List<String> getAttributeValuesByName(@PathVariable String attrName) {
        QueryWrapper<ProductAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_name", attrName);
        queryWrapper.select("DISTINCT attr_value");
        queryWrapper.orderByAsc("attr_value");
        List<ProductAttribute> attributes = productAttributeMapper.selectList(queryWrapper);
        
        return attributes.stream()
                .map(ProductAttribute::getAttrValue)
                .filter(value -> value != null && !value.trim().isEmpty())
                .distinct()
                .collect(Collectors.toList());
    }
}
